/**
 * Created by Mic on 16/2/25.
 */

var Player = require('./player');
var Robot = require('./robot');
var logger = require('pomelo-logger').getLogger(__filename);
var consts = require('../../consts/consts');
var _ = require('underscore');

var PlayerPool = function () {
    this.playerList = new Array(3);
};

module.exports = PlayerPool;

var handler = PlayerPool.prototype;

handler.addPlayer = function (seatIndex, data, value, desk) {
    var player = new Player(seatIndex, data, desk);
    this.playerList[seatIndex] = player;
    this.ready(player, value);

    return player.baseInfo();
};
handler.addRobot = function (seatIndex, data, desk) {
    var robot = new Robot(seatIndex, data, desk);
    this.playerList[seatIndex] = robot;
    robot.ready(1);
    return robot.baseInfo();
};
handler.ready = function (playerInfo, value) {
    var player = this.getPlayerByUuid(playerInfo.uuid);
    player.ready(value);
};

handler.getPlayerByIndex = function (index) {
    var player = this.playerList[index % 3];
    if (!player) {
        logger.error('找不到此玩家 ' + index);
        return null;
    }
    return player;
};

handler.getPlayerByUuid = function (playerId) {
    var player = _.find(this.playerList, function (p) {
        if (p)
            return p.uuid == playerId;
    });
    if (!player) {
        logger.error('找不到此玩家 ' + playerId);
        return null;
    }
    return player;
};

handler.getPlayersBaseInfo = function () {
    var infos = [];
    _.each(this.playerList, function (p) {
        if (p) {
            infos.push(p.baseInfo());
        } else {
            infos.push(null);
        }
    });

    return infos;
};

handler.notifyJiao = function (seatIndex) {
    var player = this.getPlayerByIndex(seatIndex);
    player.jiao();
};
handler.notifyDizhu = function (index, dipai) {
    var player = this.getPlayerByIndex(index);
    player.notifyDizhu(dipai);
};
handler.notifyDouble = function () {
    _.each(this.playerList, function (p) {
        if (p)
            p.double();
    });
};
handler.notifyPlay = function (index, ondesk, remainsArr, dizhu, pass, remains) {
    var player = this.getPlayerByIndex(index);
    player.notifyPlay(index, ondesk, remainsArr, dizhu, pass, remains);
};
handler.playedCards = function (index, value) {
    var player = this.getPlayerByIndex(index);
    player.takeAwayCards(value);
};
handler.checkGameOver = function (dizhuIndex) {
    var player = _.find(this.playerList, function (p) {
        return p.getCards() == null || p.getCards().length == 0;
    });
    if (!!player) {
        logger.fatal('游戏结束 ,玩家胜利 ' + player.seatIndex);
        return {spring: this.getSpring(dizhuIndex), winIndex: player.seatIndex};
    } else {
        return false;
    }
};

handler.getPlayerCardsByIndex = function (index) {
    var player = this.getPlayerByIndex(index);
    logger.fatal(player.getCards());
};

//当前玩家的所有牌以及其他玩家的牌的个数
handler.getRemainsCard = function (index) {
    var remainsCards = [];
    _.each(this.playerList, function (p) {
        if (p.seatIndex == index) {
            remainsCards.push(p.cards);
        } else {
            remainsCards.push(p.cards.length);
        }
    });
    return remainsCards;
};
//计算春天
handler.getSpring = function (dizhuIndex) {
    var playRound = [];
    var spring = -1;
    _.each(this.playerList, function (p) {
        playRound.push(p.getPlayRound());
    });
    var dizhuPlayRound = playRound.splice(dizhuIndex, 1);

    if (_.compact(playRound).length == 0) {
        //春天
        spring = consts.Desk.Code.Dizhu_spring;
    } else if (dizhuPlayRound[0] == 1) {
        //反春天
        spring = consts.Desk.Code.Farmer_spring;
    } else {
        //没有春天
        spring = consts.Desk.Code.No_spring;
    }

    return spring;
};
handler.getGameCoins = function (winIndex, dizhuIndex, deskBeishu, baseBet) {
    var gameCoins = [];
    var finalGameCoins = new Array(3);
    var playerBeishu = [];
    var nongminTotalBeishu = 0;

    _.each(this.playerList, function (p, i) {
        if (p) {
            playerBeishu.push(p.getBeishu());
            if (i != dizhuIndex) {
                nongminTotalBeishu += p.getBeishu();
            }
        }
    });

    var reCount = false; //是否重新计算
    var reOvertake = false; //看是否有人赢的钱超过自己
    _.each(this.playerList, function (p,i) {
        var pCoins = p.getGameCoins(winIndex, dizhuIndex, deskBeishu, playerBeishu, baseBet);
        //返回的是不够的或者够的
        if (!pCoins.enough) {
            reCount = true;
        }
        if (pCoins.overtake) {
            reOvertake = true;
        }
        console.error(i,pCoins);
        gameCoins.push(pCoins);
    });
    //重新计算
    if (reCount) {
        console.error("有人金币不够啊");
        if (winIndex == consts.Desk.Code.Dizhu_win) {
            console.log("地主赢了,把没钱的钱扣完");
            var dizhuCoins = 0;
            if (reOvertake) {
                dizhuCoins = gameCoins[dizhuIndex].gameCoin;
                var dizhuShouldCoin = 0;
                _.each(gameCoins, function (g, i) {
                    if (i != dizhuIndex) {
                        var coin = -(g.beishu / nongminTotalBeishu) * dizhuCoins;
                        var farmCost = (coin > g.gameCoin) ? g.gameCoin : coin;
                        dizhuShouldCoin += Math.abs(farmCost);
                        finalGameCoins[i] = farmCost.toFixed(0);
                    }
                });
                finalGameCoins[dizhuIndex] = dizhuShouldCoin;
            } else {
                _.each(gameCoins, function (g, i) {
                    if (i != dizhuIndex) {
                        dizhuCoins += g.gameCoin;
                        finalGameCoins[i] = g.gameCoin;
                    }
                });
                finalGameCoins[dizhuIndex] = Math.abs(dizhuCoins);
            }
        } else {
            console.log("地主输了,按照加倍的份额进行扣除");
            if (reOvertake) {
                var dizhuCoins = 0;
                _.each(gameCoins, function (g, i) {
                    if (i != dizhuIndex) {
                        var coin = (g.beishu / nongminTotalBeishu) * gameCoins[dizhuIndex].gameCoin;
                        if (g.overtake) {
                            var finalCoin = ( coin > g.gameCoin ) ? g.gameCoin : coin;
                            finalCoin = Math.abs(finalCoin).toFixed(0);
                            finalGameCoins[i] = finalCoin;
                            dizhuCoins += finalCoin;
                        }
                    }
                });
                finalGameCoins[dizhuIndex] = -dizhuCoins;
            } else {
                _.each(gameCoins, function (g, i) {
                    if (i == dizhuIndex) {
                        finalGameCoins[i] = g.gameCoin;

                    } else {
                        var coin = (g.beishu / nongminTotalBeishu) * gameCoins[dizhuIndex].gameCoin;
                        finalGameCoins[i] = Math.abs(coin).toFixed(0);
                    }
                });
            }
        }
    } else {
        //console.error("是你吧");
        if(reOvertake){
            var dzCoins = 0;
            dzCoins = gameCoins[dizhuIndex].gameCoin;
            //console.error("不应该赢这么多吧",dzCoins);
            _.each(gameCoins, function (g, i) {
                if (i != dizhuIndex) {
                    var coin = -(g.beishu / nongminTotalBeishu) * dzCoins;
                    //var farmCost = (coin > g.gameCoin) ? g.gameCoin : coin;
                    //console.error("计算 ",coin);
                    finalGameCoins[i] = coin.toFixed(0);
                }
            });
            finalGameCoins[dizhuIndex] = dzCoins;
        }else{
            _.each(gameCoins, function (g, i) {
                finalGameCoins[i] = g.gameCoin;
            });
        }

    }
    _.each(this.playerList, function (p, i) {
        if (p) {
            console.error(i," 入账 ",finalGameCoins[i]);
            p.setMoney(finalGameCoins[i]);
        }
    });

    //返回的是每个玩家的输赢金币数
    return finalGameCoins;
};
//所有牌
handler.getRemainsCards = function () {
    var remainsCards = [];
    _.each(this.playerList, function (p) {
        remainsCards.push(p.getCards());
    });
    return _.flatten(remainsCards);
};
handler.resetPlayer = function () {
    _.each(this.playerList, function (p) {
        if (p)
            p.reset();
    });
};
//得到掉线的玩家
handler.getDisPlayer = function () {
    var disPlayer = [];
    _.each(this.playerList, function (p) {
        if (!!p && typeof p.getStatus == 'function' && p.getStatus() == consts.Player.Status.Disconnect) {
            disPlayer.push(p.baseInfo());
        }
    });
    return disPlayer;
};
handler.leave = function (playerInfo) {
    logger.info(playerInfo.uuid + '  退出桌子');
    var player = this.getPlayerByUuid(playerInfo.uuid);
    if (!!player) {
        this.playerList[player.seatIndex] = null;
    }
};
//如果超时踢出未准备的
handler.kickNotReady = function () {
    var notReadyPlayers = [];
    _.each(this.playerList, function (p) {
        if (p && !!p.readyStatus == false) {
            notReadyPlayers.push(p);
        }
    });
    return notReadyPlayers;
};
handler.checkAllReady = function () {
    var readyCount = 0;

    _.each(this.playerList, function (p) {
        if (p && !!p.readyStatus) {
            readyCount++;
        }
    });
    return readyCount === 3;
};

handler.deskFee = function (deskFee, callBack) {
    _.each(this.playerList, function (p) {
        if (p) {
            p.setMoney(-deskFee);
        }
    });
    callBack();
};